package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Author 王加鑫
 * @Date 2021/09/09 21:39
 * @Since JDK 1.8
 */
@Service
@Slf4j
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 上传小视频
     * @param picFile
     * @param videoFile
     * @return
     */
    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();

        //查询用户发布权限是否被冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("3")){
            return false;
        }

        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1); //默认公开
        //上传封面图片
        try {
            PicUploadResult picUploadResult = picUploadService.upload(picFile);
            video.setPicUrl(picUploadResult.getName()); //图片路径
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), ".", true), //取.文件的后缀名， true代表是最后一个点
                    null);
            //设置视频url
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            String videoId = this.videoApi.saveVideo(video);
            return StrUtil.isNotEmpty(videoId);
        } catch (Exception e) {
            log.error("发布小视频失败！file = " + picFile.getOriginalFilename() , e);
        }
        return false;
    }

    /**
     * 小视频列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(user.getId(),page,pageSize);
        List<Video> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //获取Video表中的所有用户id
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        if(CollUtil.isEmpty(userInfoList)){
            return pageResult;
        }

        List<VideoVo> videoVos = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = new VideoVo();
            videoVo.setUserId(record.getUserId());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setCover(record.getPicUrl());
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(record.getId().toHexString()))); //TODO 点赞数量
            videoVo.setCommentCount(Convert.toInt(this.videoApi.queryVideoCommentCount(videoVo.getId()))); //TODO 评论数量
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(),record.getId().toHexString()) == true ? 1:0); //TODO 是否点赞
            videoVo.setHasFocus(this.videoApi.isFollowUser(user.getId(),videoVo.getUserId()) == true ? 1:0); //TODO 是否关注
            for (UserInfo userInfo : userInfoList) {
                videoVo.setNickname(userInfo.getNickName());
                videoVo.setAvatar(userInfo.getLogo());
                videoVo.setSignature(userInfo.getTags());
            }
            videoVos.add(videoVo);
        }
        pageResult.setItems(videoVos);
        return pageResult;
    }

    /**
     * 视频点赞
     * @param videoId
     * @return
     */
    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.likeComment(user.getId(),videoId);
        if(result){
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 视频取消点赞
     * @param videoId
     * @return
     */
    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.disLikeComment(user.getId(),videoId);
        if(result){
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 小视频评论列表
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentsList(String videoId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //查询mongodb中的Comment表中数据
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(videoId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        User user = UserThreadLocal.get();
        //查询用户信息
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>().in("user_id", userIdList).orderByDesc("created");
        //查询mysql中的UserInfo表中数据
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        if(CollUtil.isEmpty(userIdList)){
            return pageResult;
        }

        //整合records，userInfoList数据到commentVoList中
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            //转换时间格式
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()),"HH:mm"));
            //是否点赞 userId:用户id publishId:用户的这条评论的id Comment表的id
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1:0); //1:点赞 0:没有点赞
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equal(record.getUserId(), userInfo.getUserId())){
                    //将用户在UserInfo表的其余数据封装进CommentVo表中
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            commentVoList.add(commentVo);
        }
        pageResult.setItems(commentVoList);
        return pageResult;
    }

    /**
     * 小视频发布评论
     * @param comment
     * @return
     */
    public Boolean saveComments(String videoId,String comment) {
        User user = UserThreadLocal.get();

        //查询用户发言权限是否被冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("2")){
            return false;
        }

        return this.quanZiApi.saveComment(user.getId(), videoId, comment);
    }

    /**
     * 视频用户关注
     * @param userId
     * @return
     */
    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.followUser(user.getId(), userId);
    }

    /**
     * 视频用户取消关注
     * @param userId
     * @return
     */
    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.disFollowUser(user.getId(), userId);
    }
}
